package casa.depesos.app.com.adapter;

import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;


import java.util.List;

import casa.depesos.app.com.databinding.CardDlgItemBinding;
import casa.depesos.app.com.dlg.CardDlg;
import casa.depesos.app.com.http.data.BankCard;

public class BankCardDlgAdapter extends RecyclerView.Adapter {

    List<BankCard> list;
    CardDlg activity;

    public BankCardDlgAdapter(CardDlg activity, List<BankCard> list) {
        this.activity = activity;
        this.list = list;
    }

    public void setData(List list) {
        this.list = list;
        notifyDataSetChanged();
    }

    public void delete(int p) {
        list.remove(p);
        notifyItemRemoved(p);
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        CardDlgItemBinding binding = CardDlgItemBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new ItemHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ItemHolder) {
            ((ItemHolder) holder).bind(position);
        }
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    class ItemHolder extends RecyclerView.ViewHolder {
        CardDlgItemBinding binding;

        ItemHolder(CardDlgItemBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        void bind(int p) {
            BankCard item = list.get(p);
            binding.name.setText(item.name);
            binding.no.setText(item.cardNo);
            itemView.setOnClickListener(v -> {
                activity.selectCard(item);
            });
        }
    }
}
